<?php

namespace App\Kuafu\Shop\Service;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Shop\Enum\AreaCacheEnum;
use App\Kuafu\Shop\Enum\AreaCodeEnum;
use App\Kuafu\Shop\Model\AreaModel;
use Illuminate\Support\Facades\Cache;
use stdClass;

class AreaService extends BaseService
{

    /**
     * 获取省市区列表
     *
     * @param int $areaId
     * @return array
     */
    public static function getAreaLists(int $areaId): array
    {
        return [
            'areaLists' => Cache::rememberForever(AreaCacheEnum::getAreaLists($areaId),
                function () use ($areaId) {
                    return AreaModel::query()->when($areaId > 0, function ($query) use ($areaId) {
                        $query->where('areaPid', $areaId);
                    })->when($areaId <= 0, function ($query) {
                        $query->where('level', AreaCodeEnum::AREA_PROVINCE);
                    })->select(['id', 'areaId', 'areaPid', 'cnShortName', 'cnFullName', 'adCode'])->get()
                                    ->sortBy('adCode')->values()->toArray();
                })
        ];
    }

    /**
     * @param string $cityCode
     * @return stdClass[]
     */
    public static function getCityGrade(string $cityCode): array
    {
        $cityInfo = AreaModel::query()
                             ->where("areaId", $cityCode)
                             ->where("level", 2)
                             ->first();

        return [
            "cityInfo" => $cityInfo ? $cityInfo->toArray() : new stdClass()
        ];

    }

    public static function getListAll()
    {
        return [
            'areaList' => Cache::remember(AreaCacheEnum::getListAll(), 86400,
                function () {
                    return AreaModel::query()
                        ->select(['id', 'areaId', 'areaPid', 'cnShortName', 'cnFullName', 'adCode', 'level'])
                        ->get()
                        ->sortBy('adCode')
                        ->values()
                        ->toArray();
                })
        ];
    }
}
